package com.shengdong.water.feature.main.fragment

import android.annotation.SuppressLint
import android.content.res.Resources
import android.os.Build
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.graphics.toColorInt
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.kongzue.dialogx.dialogs.BottomDialog
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.dialogs.CustomDialog.ALIGN
import com.kongzue.dialogx.interfaces.DialogLifecycleCallback
import com.kongzue.dialogx.interfaces.OnBindView
import com.shengdong.water.R
import com.shengdong.water.base.BaseVMFragment
import com.shengdong.water.code.adapter.MapOutletAdapter
import com.shengdong.water.code.bean.LatLng
import com.shengdong.water.code.viewmodel.MainViewModel
import com.shengdong.water.code.viewmodel.MapViewModel
import com.shengdong.water.code.widget.WheelView
import com.shengdong.water.databinding.FragmentMapBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.collections.filter
import kotlin.collections.map

@AndroidEntryPoint
class MapFragment: BaseVMFragment< FragmentMapBinding,MapViewModel>() {

    override fun getLayoutId() = R.layout.fragment_map

    override fun createViewModel(): MapViewModel  =  viewModelProvider(MapViewModel::class.java)

    private val mapAdapter = MapOutletAdapter()


    override fun initViews() {
        binding.viewModel = viewModel

        binding.ivFilter.setOnClickListener {
            showFilterDialog()
        }
        setupWebView()
    }

    private fun showFilterDialog() {
        CustomDialog.build().setDialogLifecycleCallback(object :
            DialogLifecycleCallback<CustomDialog>() {
            override fun onShow(dialog: CustomDialog?) {
                super.onShow(dialog)
                // Set dialog width to match parent when shown
            }

            override fun onDismiss(dialog: CustomDialog?) {
                super.onDismiss(dialog)
            }
        }

        ).setCustomView(object : OnBindView<CustomDialog>(R.layout.dialog_map_filter) {
            override fun onBind(dialog: CustomDialog, v: View) {
                val recyclerview = v.findViewById<RecyclerView>(R.id.rv_list)
                recyclerview.layoutManager = LinearLayoutManager(context)
                recyclerview.setHasFixedSize(true)
                recyclerview.adapter = mapAdapter

                mapAdapter.setOnItemSelectedListener { outlet ->
                    println(outlet)
                }

                v.findViewById<AppCompatTextView>(R.id.tv_confirm).setOnClickListener {
                    dialog.dismiss()
                }

                v.findViewById<AppCompatTextView>(R.id.tv_cancel).setOnClickListener {
                    dialog.dismiss()
                }
            }
        }).setFullScreen(true).setMaskColor("#66000000".toColorInt()).setAlign(ALIGN.BOTTOM).show()
    }



    @SuppressLint("SetJavaScriptEnabled")
    private fun setupWebView() {
        val webView = binding.webview
        WebView.setWebContentsDebuggingEnabled(true)
        val webSettings = webView.settings
        webSettings.javaScriptEnabled =true
        webSettings.domStorageEnabled = true
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

        // 添加JavaScript接口
        webView.addJavascriptInterface(WebAppInterface(), "Android");
        webView.webViewClient = WebViewClient()
        webView.loadUrl("file:///android_asset/tianditu_map.html")
    }

    override fun initData(){
        viewModel.getDistricts()
        viewModel.getOutletInfoOnMap()
    }

    @SuppressLint("JavascriptInterface")
    override fun dataObserver() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {

                launch {
                    viewModel.districts.collect { districts ->
                        districts?.let {

                            val long = it.data.district[0].center.lng
                            val lat = it.data.district[0].center.lat
                            println("""getDistricts:$long$lat""")
                            binding.webview.evaluateJavascript("javascript:initMap($long, $lat)",null)
                            drawFence(it.data.district[0].boundary)
                        }
                    }
                }

                launch {
                    viewModel.outlets.collect { outlets ->
                        outlets?.let {
                            println(it.outletList)
                            val markersJson = Gson().toJson(it.outletList)
                            addMarkersToMap(markersJson)
                            mapAdapter.setItems(it.outletTable)

                        }

                    }
                }

            }
        }
    }


    private fun drawFence(polygonData: String) {
        // 解析MULTIPOLYGON数据
        val coordinates = parseMultiPolygon(polygonData)
        val pointsJson = Gson().toJson(coordinates)

        // 调用JavaScript函数绘制围栏
        val jsCode = "javascript:drawFence($pointsJson);"
        binding.webview.evaluateJavascript(jsCode, null)
    }

    private fun parseMultiPolygon(data: String): List<LatLng> {
        // 移除MULTIPOLYGON和括号，只保留坐标
        val coordsStr = data.replace("MULTIPOLYGON(((", "")
            .replace(")))", "")
        // 分割坐标对
        return coordsStr.split(",").map { coord ->
            val (lng, lat) = coord.trim().split(" ")
            LatLng(lng.toDouble(), lat.toDouble())
        }
    }

    private fun addMarkersToMap(markersJson: String) {
        val jsCode = "javascript:addMarkers($markersJson);"
        binding.webview.evaluateJavascript(jsCode, null)
    }

    inner class WebAppInterface {
        @JavascriptInterface
        fun onFenceClick(json: String) {
        }

        @JavascriptInterface
        fun onMarkerClick(id: String, name: String) {

        }

    }


}

